package cn.jit.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import cn.jit.po.Question;
import cn.jit.po.QuestionVo;
import cn.jit.po.User;
import cn.jit.po.UserExam;
import cn.jit.po.UserExamVo;
import cn.jit.service.QuestionService;
import cn.jit.service.UserExamService;
import cn.jit.service.UserService;
import cn.jit.util.ExcelUtils;
import cn.jit.util.MD5Util;
import cn.jit.util.ResponseObject;
import cn.jit.util.ResponseUtil;
import cn.jit.util.UploadFileUtil;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/admin")
public class AdminController {
	
	@Resource
    private UserService userService;
	
	@Resource
    private QuestionService questionService;
	
	@Resource
	private UserExamService userExamService;
	
	/******************* 前端界面 开始 ********************/
	
	@RequestMapping(value="",method=RequestMethod.GET)
    public String adminCenter() {
		return "admin_center";
	}
	
	@RequestMapping(value="/user",method=RequestMethod.GET)
    public String adminUserList(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("loginedUsername");
		if (username == null) {
			return "login";
		}
		
		return "admin_user_list";
	}
	
	@RequestMapping(value="/user/detail/{id}",method=RequestMethod.GET)
    public ModelAndView userDetail(@PathVariable Integer id,
    		HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		HttpSession session = request.getSession();
		Integer userType = (Integer) session.getAttribute("loginedUserType");
		if (userType != 1) {
			mv.setViewName("operation_info");
			mv.addObject("info", "查看失败");
			mv.addObject("cause", "不是管理员不能查看系统用户的信息");
			return mv;
		}
		
		User user = userService.getUser(id);
		UserExam ue = new UserExam();
		ue.setUserId(id);
		UserExamVo userExamVo = userExamService.getUserExamList(ue);
		mv.setViewName("user_detail");
		mv.addObject("user", user);
		if (userExamVo != null) {
			mv.addObject("examList", userExamVo.getExamList());
		}
		return mv;
	}
	
	@RequestMapping(value="/question",method=RequestMethod.GET)
    public String adminQuestionList() {
		// TODO: 分页
		return "question";
	}
	
	@RequestMapping(value="/question/add",method=RequestMethod.GET)
    public String adminQuestionAdd() {
		return "question_add";
	}
	
	@RequestMapping(value="/question/addByExcel",method=RequestMethod.GET)
    public String adminQuestionAddByExcel() {
		return "question_add_by_excel";
	}
	
	@RequestMapping(value = "/question/downloadExcelTemplete", produces = "application/octet-stream;charset=UTF-8")
	public ResponseEntity<byte[]> downloadExcelTemplete(HttpServletRequest request) throws IOException {
		//文件名称
		String fileName = "templete.xlsx";
		
		// 指定文件,必须是绝对路径
		String path = request.getSession().getServletContext().getRealPath("/resources/upload/excel");
		String fileUrl = path + File.separator + fileName;
		System.out.println("path: " + path);
		File file = new File(fileUrl);
		
		// 下面开始设置HttpHeaders,使得浏览器响应下载
		HttpHeaders headers = new HttpHeaders();
		// 设置响应方式
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 设置响应文件
		headers.setContentDispositionFormData("attachment", fileName);
		// 把文件以二进制形式写回
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
	}
    
	@RequestMapping(value="/question/detail/{id}",method=RequestMethod.GET)
    public ModelAndView questionDetail(@PathVariable Integer id,HttpServletRequest request,HttpServletResponse response) {
		Question question = new Question();
		question.setQuestionId(id);
		Question result = questionService.getOneQuestion(question);
		
		ModelAndView mv = new ModelAndView();
		
		if (request == null) {
			mv.setViewName("operation_info");
			mv.addObject("info", "未查到相关信息!");
			return mv;
		}
				
		mv.setViewName("question_detail");
		mv.addObject("question", result);
		return mv;
	}
	
	/******************* 前端界面 结束 ********************/
	
	/******************* 后端接口 开始 ********************/
	@RequestMapping(value="/back_user",method=RequestMethod.GET)
    public void login(User user,HttpServletRequest request,HttpServletResponse response) {
		ResponseObject responseObject = new ResponseObject();
		
		ArrayList<User> userList = userService.getUsers(user);
		
		responseObject.setCode(200);
		responseObject.setIsSuccess(true);
		responseObject.setMsg("查询成功！");
		responseObject.setData(userList);
		
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        
        String resp = gson.toJson(new ResponseObject(200,true,"success",userList));
		
		ResponseUtil.writeJson(response, resp);
		return ;
    }
	
	@RequestMapping(value = "/question/back_addByExcel", method = RequestMethod.POST)
	public ModelAndView addQuestioonByExcel(@RequestParam("questionExcel") MultipartFile questionExcel,
			HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("operation_info");
		// 上传的目标文件夹
		String path = request.getSession().getServletContext().getRealPath("/resources/upload/excel");
		System.out.println("存放的path：" + path);

		// 原文件名
		String fileName = questionExcel.getOriginalFilename();
		System.out.println("filename:" + fileName);

		// 新文件名
		SimpleDateFormat stFormat = new SimpleDateFormat("yyyymmddhhMMSS");
		String newfileName = stFormat.format(new Date());

		String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		System.out.println("上传文件的后缀是:" + suffix);

		String[] allowedSuffix = { ".xlsx" };
		if (!UploadFileUtil.fileSuffixIsAllowed(allowedSuffix, suffix)) {
			mv.addObject("info", "上传失败!");
			mv.addObject("cause", "文件后缀只能是: .xlsx");
			return mv;
		}

		newfileName += suffix;
		System.out.println("新的文件名是:" + newfileName);

		File dir = new File(path, newfileName);

		if (!dir.exists()) {
			System.out.println("文件不存在！要准备创建！");
			dir.mkdirs();
		}

		questionExcel.transferTo(dir);

		String readPath = path + File.separator + newfileName;
		
		System.out.println("readPath: " + readPath);
		
		List<QuestionVo> questionVos = ExcelUtils.getInstance().readExcel2Objects(readPath, QuestionVo.class, 0);
		System.out.println("读取Excel至对象数组(支持类型转换)：");
		for (QuestionVo st : questionVos) {
			System.out.println(st);
		}
		
		if (!questionService.addBatchQuestion(questionVos)) {
			mv.addObject("info", "上传失败!");
			mv.addObject("cause", "添加题目到数据库失败!");
			return mv;
		}
		
		mv.addObject("info", "题目上传成功");
		return mv;
	}
	
	
	/******************* 后端接口 结束 ********************/
}
